// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Vue from 'vue'
import { API_MAP, transList } from '@admin/views/Secure/mixDevice/store/actions'

// ============================== 导出异步调用 ============================== //

export default {
  // —————————————————————————————— 下拉框 —————————————————————————————— //

  async remoteSelect({ state: { selectParam: { nextIdList: ids, ...param } }, getters }) {
    if (CORE.isEmpty(ids)) return

    const TYPE = ['2', '3', '4', '16', '0'] // [门禁，车库，防区，巡更，IOT]
    const typeList = getters['map/GETTER'].typeDict.map(([type]) => type) // typeDict 已删除
    const iotType = typeList.filter((type) => !TYPE.includes(type))

    const multi = TYPE.map((type) => { // 生成二维数组
      const deviceCategoryId = type === '0' ? iotType.join() : typeList.includes(type) ? type : ''
      if (!deviceCategoryId) return ids.map(() => Promise.resolve([]))
      return ids.map((id) => API_MAP[type].getSelect({ ...param, deviceCategoryId, areaId: id }))
    })

    const promiseList = multi.reduce((result, arr) => [...result, ...arr], []) // 转为一维数组
    const resp = await Promise.all(promiseList.map((promise) => promise.catch(() => null))) // 部分成功，也要返回

    resp.forEach((data, i) => {
      if (!data) return // 异常结果不处理，下次可重新查询

      const node = getters.treeMap[ids[i % ids.length]] // 定位区域节点
      const getFilter = (x) => data.filter((item) => item.deviceCategoryId === x) // 按类型过滤

      if (i < ids.length) Vue.set(node, 'device_2', transList(data)) // 门禁点位
      else if (i < ids.length * 2) Vue.set(node, 'device_3', transList(data)) // 车库点位
      else if (i < ids.length * 3) Vue.set(node, 'device_4', transList(data)) // 入侵防区
      else if (i < ids.length * 4) Vue.set(node, 'device_16', transList(data)) // 巡更点位
      else iotType.forEach((x) => Vue.set(node, `device_${x}`, transList(getFilter(x), '', true))) // IOT设备
    })
  },
}
